/*
sem_init(&semaphore,0,count)
sem_wait(&semaphore)
sem_trywait(&semaphore)
sem_post(&semaphore)
sem_destroy(&semaphore)
*/



#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>


using namespace std;

sem_t semaphore;
bool run= false;

void signal_handler(int arg)
{
	run = true;
	cout << "get ctrl+c" << arg << endl;
}


void* accessResource(void* arg)
{
	while(!run)
	{
		sem_wait(&semaphore);
		cout << "thread access resource:" << *(int*)arg << endl;
		sem_post(&semaphore);
		sleep(1);
	}

	return nullptr;
}


int main(int argc,char** argv)
{
	pthread_t t1,t2;
	int arg1 = 1,arg2 = 2;

	signal(SIGINT,signal_handler);

	sem_init(&semaphore,0,1);

	pthread_create(&t1,nullptr,accessResource,(void*)&arg1);
	pthread_create(&t2,nullptr,accessResource,(void*)&arg2);	
	
	while(!run)
	{	
		//sem_post(&semaphore);
		sleep(1);
	}
	
	pthread_join(t1,nullptr);
	pthread_join(t2,nullptr);

	sem_destroy(&semaphore);

	return 0;
}






